package com.example.springboot.service.impl;

import com.example.springboot.dao.UserRpository;
import com.example.springboot.pojo.Base;
import com.example.springboot.pojo.User;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRpository userRpository;

    @Autowired
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    String mailUsername;
    @Override
    public Base registry(User user,HttpSession session) {
        User T_user=userRpository.findByUserName(user.getUserName());
        //判断用户是否被注册
        if (T_user!=null) {
        return new Base(null,"用户被注册！",1,null);
        }
        if (session.getAttribute("code")!=null) {
            if (user.getCode().equals(session.getAttribute("code").toString())) {
                User user1 = userRpository.saveAndFlush(user);
                if (user1!=null) {
                    return new Base(null,"验证码正确,注册成功",1,null);
                }
            }else {
                return new Base(null,"验证码错误",0,null);
            }
        }else {
            return new Base(null,"未发送验证码",0,null);
        }
        return null;
    }

    @Override
    public Base send(Map map, HttpSession session) {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setTo(map.get("mail").toString());
        message.setSubject("注册验证码");
        message.setFrom(mailUsername);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            stringBuffer.append(new Random().nextInt(10));
        }
        message.setText(stringBuffer.toString());
        javaMailSender.send(message);
        session.setAttribute("code",stringBuffer.toString());
        return new Base(null,"发送验证码",1,null);
    }

    @Override
    public Base login(User user,HttpSession session){
        User byUserName = userRpository.findByUserName(user.getUserName());
        if (byUserName==null) {
            return new Base(null,"用户未注册",0,null);
        }
        if (!byUserName.getPassword().equals(user.getPassword())) {
            return new Base(null,"密码错误",0,null);
        }
        session.setAttribute("user",user);
        return new Base(null,"登录成功",1,null);
    }
}
